Skip to content

Fixes #33436: Refuse SPARQL SERVICE hidden inside EXISTS - #37249

Merged
pmbrull merged 3 commits into
mainfrom
pmbrull/sparql-service-in-exists
Nov 6, 2026
Merged

pmbrull merged 3 commits into
mainfrom
pmbrull/sparql-service-in-exists

Conversation

@pmbrull

@pmbrull pmbrull commented Nov 6, 2026 •

Copy link
Copy Markdown
Member

Describe your changes:

Fixes #33436

SparqlFederationGuard collected SERVICE endpoints by walking only the WHERE pattern with Jena's ElementWalker, which never descends into expressions, EXISTS / NOT EXISTS blocks or subquery projections. A SERVICE nested in EXISTS { … } — inside FILTER, BIND, LET, UNFOLD, the projection, GROUP BY, HAVING, an aggregate, ORDER BY, or written as a bare EXISTS { … } pattern element (Jena's default ARQ syntax accepts it) — passed the guard and was executed.

#33436 scoped this to the admin /v1/rdf/sparql* endpoints, where Fuseki executes the SERVICE and the gap bypasses rdf.federation.allowedEndpoints. The same guard also fronts the glossary and ontology SPARQL endpoints (POST /v1/glossaries/{id}/sparql, POST /v1/ontologies/{id}/sparql). Those are open to any user who can view the glossary or ontology and run the query inside the OpenMetadata server, so there a hidden SERVICE made the server itself send an HTTP request to a host of the caller's choosing. AgentSparqlQueryInspector (/v1/rdf/sparql/agent) followed the expression positions but not a bare EXISTS { … } element.

The guard, the glossary endpoint and OntologySparqlQueryService came in with #28042, which is on the 2.1 branch and in the 2.1.0-rc1 pre-release, so this fix needs to reach 2.1 before 2.1.0 ships.

Changes:

  • SparqlQueryWalker (new, rdf/federation): one traversal of every pattern element and expression of a query, following everything ElementWalker skips — FILTER / BIND / LET / UNFOLD expressions, EXISTS / NOT EXISTS as expressions and as bare elements, subqueries, and the projection, GROUP BY, HAVING, aggregate and ORDER BY expressions.
  • SparqlFederationGuard walks queries and update WHERE clauses with it.
  • AgentSparqlQueryInspector takes its elements and expressions from the same walker instead of its own partial recursion. Its checks (GRAPH, dataset, SERVICE, java:, CALL, eval) are unchanged; bare EXISTS / NOT EXISTS are now covered for all of them.
  • OntologySparqlQueryService — the only in-process SPARQL executor (glossary, ontology release and ontology draft queries) — sets Service.httpServiceAllowed = false on every execution. Its model is self-contained, so SERVICE is never legitimate there, and the server cannot send a request whatever a syntax check misses.

Type of change:

  • Bug fix

High-level design:

  • Approach. Two checkers each carried their own copy of "where can a graph pattern hide in a query", and both copies were incomplete in different places. The fix moves that knowledge into one walker that both use, and adds an execution-time backstop where the server runs SPARQL itself.
  • How the pieces interact. SparqlQueryWalker.walk(query, elementVisitor, expressionVisitor) runs ElementWalker with the caller's visitor and an after-visitor that follows expressions, EXISTS elements and subqueries; every element found anywhere goes to the caller's element visitor, every expression (each function argument on its own) to the expression visitor. The guard passes an endpoint collector; the agent inspector passes itself plus its expression checks.
  • Alternatives rejected.
    • Teach only the guard's collector to recurse into expressions: leaves a third copy of the traversal to drift, the way the inspector's copy already had (bare EXISTS).
    • Walk the compiled algebra instead of the syntax: same coverage, but every check would have to be rewritten against Op / Expr walkers.
    • Disable HTTP SERVICE globally in ARQ.getContext(): would change process-wide ARQ state that other code in the server (and Collate) shares; scoped to the one in-process executor instead.
  • Compatibility. A query with SERVICE inside EXISTS that used to run now gets 403 (FEDERATION_NOT_ALLOWED on the agent endpoint), exactly as a top-level SERVICE already did. With rdf.federation.enabled and an allowlist, an allowlisted endpoint inside EXISTS still passes the guard on the admin endpoints, as a top-level one does. The glossary and ontology endpoints never allowed SERVICE (their guard is built with no federation config) and now cannot execute it either. No schema, API shape or migration change.

Tests:

Use cases covered

  • A user with no roles queries a glossary ontology: a plain query works; SERVICE at top level, inside a projected EXISTS, inside FILTER EXISTS, or inside a bare EXISTS element is refused with 403, and a loopback HTTP endpoint standing in for an internal host receives zero requests.
  • A viewer querying an ontology (POST /v1/ontologies/{id}/sparql) is refused SERVICE inside a projected EXISTS with 403.
  • Against a real Fuseki: admin /v1/rdf/sparql refuses SERVICE inside a projected EXISTS, FILTER EXISTS, a bare NOT EXISTS and an ORDER BY EXISTS; /v1/rdf/sparql/update refuses it inside BIND(EXISTS …) of an INSERT … WHERE; /v1/rdf/sparql/agent and the non-admin MCP sparql_query tool refuse it inside bare EXISTS / NOT EXISTS with FEDERATION_NOT_ALLOWED. The target is Fuseki's own ping endpoint, which Fuseki can always reach.
  • The admin MCP sparql_query path (federation guard) refuses SERVICE inside a bare or projected EXISTS.
  • In-process execution sends no request even when the guard is configured to allowlist the endpoint (real Jena + loopback HTTP endpoint).

Unit tests

  • I added unit tests for the new/changed logic.
  • Files added/updated:
    • SparqlFederationGuardTest — 21 hidden positions (FILTER / NOT EXISTS, nested function args, BIND, LET, UNFOLD, projection, GROUP BY, HAVING, aggregate, ORDER BY, subquery projection, nested EXISTS, OPTIONAL, LATERAL, bare EXISTS / NOT EXISTS, ASK, CONSTRUCT, DESCRIBE), a hidden variable endpoint, a hidden endpoint next to an allowlisted one, an EXISTS without SERVICE staying allowed, and SERVICE hidden in an update WHERE.
    • SparqlQueryWalkerTest (new) — every nested expression reaches the expression visitor; patterns inside expressions and subqueries reach the element visitor.
    • AgentSparqlQueryValidatorTest — bare EXISTS / NOT EXISTS carrying SERVICE, GRAPH and a java: predicate.
    • OntologySparqlQueryServiceTest — guard rejection with zero requests to a loopback endpoint; execution refuses SERVICE (top level, projected and BIND EXISTS) even when the guard allowlists it; a refused SERVICE inside a filter never matches.
    • SparqlQueryToolTest (openmetadata-mcp) — rejectsDisallowedFederation now also covers bare and projected EXISTS.
  • Fails on main: the new cases were run against the unmodified main code first — 34 failures/errors (all 21 hidden positions passed the guard; the loopback endpoint was contacted and its row came back). All pass with the fix.
  • Coverage on changed classes (JaCoCo, -Pstatic-code-analysis, over SparqlFederationGuardTest, SparqlQueryWalkerTest, OntologySparqlQueryServiceTest, AgentSparqlQueryValidatorTest, AgentSparqlQueryInspectorTest, AgentSparqlServiceTest, RdfSparqlServiceTest, OntologyDraftQueryTest, OntologySparqlQueryValidatorTest — 172 tests, all passing): SparqlQueryWalker 100% (50/50 lines), SparqlFederationGuard 98.7% (74/75), AgentSparqlQueryInspector 95% (38/40; its JavaSchemePathRejector inner class, untouched here, is 4/35), OntologySparqlQueryService 87.5% (119/136; every missed line is a pre-existing format, inference or protocol-dataset branch — the changed execution path is covered).

Backend integration tests

  • I added integration tests in openmetadata-integration-tests/ for new/changed API endpoints.
  • Files added/updated: GlossaryOntologyQueryIT (new), OntologyDraftQueryIT, RdfResourceIT, AgentSparqlResourceIT, RdfMcpKnowledgeGraphIT, FusekiTestImage (SELF_PING_URL).
  • The two MCP cases (SparqlQueryToolTest, RdfMcpKnowledgeGraphIT) were added after review and not run against main; they go through the guard and the agent inspector, whose failure on main for the same shapes is shown by SparqlFederationGuardTest and AgentSparqlQueryValidatorTest.
  • Fails on main, against a real stack (rdf lane, MySQL + Elasticsearch, Fuseki openmetadata/fuseki:6.2.0-318ff87), the new ITs with the four main-code files reverted:
    • /v1/rdf/sparql: FILTER EXISTS and bare NOT EXISTS returned 200 after ~17 s each while Fuseki issued the SERVICE calls; projected and ORDER BY EXISTS returned 500 from Fuseki's failed SERVICE call. /v1/rdf/sparql/update: 500.
    • /v1/rdf/sparql/agent, bare EXISTS / NOT EXISTS: 200.
    • Glossary (GlossaryOntologyQueryIT, also re-run in the parallel lane with RDF off): projected EXISTS → 500 after the server fetched the loopback endpoint; FILTER EXISTS and a bare EXISTS → 200, no refusal. The top-level SERVICE case was already 403 on main and is kept as a control.
    • Ontology, viewer, projected EXISTS (OntologyDraftQueryIT#aViewerIsRefusedAServiceClauseHiddenInsideAnExpression): 400 — the query got past the guard and failed later, on the missing active release.
  • The SPARQL admission guard admits two concurrent queries per user and answers a third with 429, before the query is even validated. The first local run hit it: the parameterized glossary cases ran in parallel as one user, and an extra admin query in the concurrent OntologyDraftQueryIT pushed an existing test there to 429. So GlossaryOntologyQueryIT runs SAME_THREAD as user3, and the new ontology case queries as user1; no other SPARQL IT uses either user. (OntologyDraftQueryIT's existing tests still run up to three admin queries concurrently, so that class can meet the limit on its own.)
  • Passing with the fix:

Local Java test run: PASSED

  • Commit: cb20d11e7e5f (base origin/main)
  • Finished: 2026-11-06 09:45 UTC · 10.4 min
  • Scope: focused; merge readiness is not established. Broader steps deferred: 8 (run --scope full).
Step Scope Classes Tests Failed Skipped Min Result
unit openmetadata-mcp (1 class), openmetadata-service (5 classes) 6 145 0 0 1.6 passed
integration mysql-elasticsearch · parallel 2 10 0 0 4.4 passed
integration mysql-elasticsearch · rdf 3 65 0 0 4.4 passed
  • Impacted, not run locally: 2 classes (listed in the details)
  • Details

Also run by hand with RDF on against a real Fuseki, since the planner puts these two classes in the parallel lane: -DintegrationTests.lane=rdf -Dit.test=GlossaryOntologyQueryIT,OntologyDraftQueryIT → 10 tests, 0 failures.

Ingestion integration tests

  • Not applicable (no ingestion changes).

Playwright (UI) tests

  • Not applicable (no UI changes).

Manual testing performed

The integration tests above are the end-to-end check: real server over HTTP, real MySQL / Elasticsearch / Fuseki containers, a user with no roles for the glossary case. To reproduce the failure, revert SparqlFederationGuard.java, AgentSparqlQueryInspector.java, OntologySparqlQueryService.java and delete SparqlQueryWalker.java, then run:

mvn -B verify -pl :openmetadata-integration-tests -am -Dspring-boot.repackage.skip=true -Pmysql-elasticsearch -DintegrationTests.lane=rdf \
  -Dit.test='RdfResourceIT#testSparqlEndpointRefusesServiceHiddenInsideExists+testSparqlUpdateEndpointRefusesServiceHiddenInsideExists,AgentSparqlResourceIT#federationInsideABareExistsBlockIsRefused,GlossaryOntologyQueryIT,OntologyDraftQueryIT#aViewerIsRefusedAServiceClauseHiddenInsideAnExpression' \
  -Dfailsafe.failIfNoSpecifiedTests=false -Dtest=NoUnitTestsInThisRun -Dsurefire.failIfNoSpecifiedTests=false

UI screen recording:

Not applicable — backend-only security fix, no UI change.

Checklist:

  • I have read the CONTRIBUTING document.

  • My PR title is Fixes <issue-number>: <short explanation>

  • My PR is linked to a GitHub issue via Fixes #<issue-number> above.

  • I have commented on my code, particularly in hard-to-understand areas.

  • For JSON Schema changes: I updated the migration scripts or explained why it is not needed. — N/A, no schema change.

  • For a UI feature or feature task: as part of PR creation, I ran the PR build in Docker with sample data and embedded a verified GitHub-hosted recording plus build/health evidence above (or explained why this requirement is not applicable). — N/A, backend only.

  • I have added tests (unit / integration / Playwright as applicable) and listed them above.

  • Self-review: I reviewed the final diff against REVIEW.md (the pr-checklist skill runs it) and fixed every 🔴 finding, or answered it on the line below.
    Reviewed by a fresh-context reviewer against REVIEW.md: first pass on the full change, second pass on the follow-up commits up to cb20d11e7e5. Fixed: 🔴 the new glossary/ontology ITs could get 429 instead of 403 under parallel execution (now SAME_THREAD and dedicated users); 🟡 MCP regressions for the bare-EXISTS gap added; 🟡 stale reason in ADR:2026-09-16-agent-sparql-execution amended (v5), then its header links relabelled (7a198e8a46d, docs only). No 🔴 answered instead of fixed.

  • Decision check: no new record. The change enforces the contract the glossary endpoint already documents ("cannot access … SERVICE endpoints") and the existing federation policy, and adds no default, limit, format or ordering. It amends ADR:2026-09-16-agent-sparql-execution (v5): one of its reasons for keeping the guard off the agent path, the guard's pattern-only walk, no longer holds now that both share SparqlQueryWalker.

  • I have added a test that covers the exact scenario we are fixing. For complex issues, comment the issue number in the test for future reference.

🤖 Generated with Claude Code

SparqlFederationGuard walked only the WHERE pattern with Jena's
ElementWalker, which does not descend into expressions, EXISTS blocks or
subquery projections. A SERVICE inside EXISTS { ... } in a FILTER, BIND,
LET, UNFOLD, the projection, GROUP BY, HAVING, an aggregate, ORDER BY,
or a bare EXISTS element passed the guard and was executed: by Fuseki on
the admin /v1/rdf/sparql endpoints, and inside the OpenMetadata server
on the glossary and ontology /sparql endpoints, which any viewer can
call. AgentSparqlQueryInspector followed the expression positions but
missed a bare EXISTS / NOT EXISTS element.

Add SparqlQueryWalker, one traversal of every element and expression of
a query, and use it in SparqlFederationGuard (queries and update WHERE
clauses) and AgentSparqlQueryInspector. OntologySparqlQueryService, the
in-process executor behind the glossary and ontology endpoints, now
refuses HTTP SERVICE in its ARQ context, so no syntax position can make
the server send a request.

Fixes #33436
The MCP sparql_query tool reaches the federation guard (admin) and the
agent inspector (non-admin); both now get a SERVICE hidden in a bare
EXISTS block. Amend the agent SPARQL decision record: its reason for
keeping the guard off the agent path no longer includes the guard's
pattern-only walk, since both share SparqlQueryWalker.

Refs #33436
@pmbrull
pmbrull requested a review from a team as a code owner November 6, 2026 09:46
@pmbrull
pmbrull requested review from TeddyCr and a balanced review from Copilot November 6, 2026 09:46

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@github-actions

github-actions Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

✅ PR checks passed

The linked issue has a description and all required Shipping project fields set. Thanks!

@github-actions github-actions Bot added Ingestion safe to test Add this label to run secure Github workflows on PRs labels Nov 6, 2026
@pmbrull

pmbrull commented Nov 6, 2026

Copy link
Copy Markdown
Member Author

Local Java test run: PASSED — details

  • Commit: cb20d11e7e5f (base origin/main)
  • The summary is in the PR description.

Tests run locally

  • unit · openmetadata-mcp (1 class), openmetadata-service (5 classes): AgentSparqlQueryInspectorTest (4 passed), AgentSparqlQueryValidatorTest (54 passed), OntologySparqlQueryServiceTest (17 passed), SparqlFederationGuardTest (0 passed), SparqlFederationGuardTest$AdversarialInputs (7 passed), SparqlFederationGuardTest$FederationDisabled (3 passed), SparqlFederationGuardTest$FederationEnabled (10 passed), SparqlFederationGuardTest$HiddenService (24 passed), SparqlFederationGuardTest$ServiceEndpointsListing (2 passed), SparqlFederationGuardTest$UpdateRequests (6 passed), SparqlQueryToolTest (16 passed), SparqlQueryWalkerTest (2 passed)
  • integration · mysql-elasticsearch · parallel: GlossaryOntologyQueryIT (8 passed), OntologyDraftQueryIT (2 passed)
  • integration · mysql-elasticsearch · rdf: AgentSparqlResourceIT (24 passed), RdfMcpKnowledgeGraphIT (21 passed), RdfResourceIT (20 passed)

Per-class counts come from the test reports, which can credit a test to the wrong class when classes run concurrently, and keep only the last run of a nested class that several test classes inherit. The summary's step totals are Maven's own counts.

Broader coverage not executed by this focused run

  • mvn -B package -pl openmetadata-mcp,openmetadata-service -am -Dspring-boot.repackage.skip=true -Dtest=AgentSparqlQueryInspectorTest,AgentSparqlQueryValidatorTest,AgentSparqlServiceTest,OntologyAiResourceTest,OntologyAiServiceTest,OntologySparqlQueryServiceTest,OntologySparqlQueryValidatorTest,RdfSparqlServiceTest,SparqlFederationGuardTest,SparqlQueryToolTest,SparqlQueryWalkerTest -Dsurefire.failIfNoSpecifiedTests=false
  • mvn -B verify -pl :openmetadata-integration-tests -am -Dspring-boot.repackage.skip=true -Pmysql-elasticsearch -DintegrationTests.lane=parallel '-Dit.test=<483 classes>' -Dfailsafe.failIfNoSpecifiedTests=false -Dtest=NoUnitTestsInThisRun -Dsurefire.failIfNoSpecifiedTests=false
  • mvn -B verify -pl :openmetadata-integration-tests -am -Dspring-boot.repackage.skip=true -Pmysql-elasticsearch -DintegrationTests.lane=global-state '-Dit.test=<34 classes>' -Dfailsafe.failIfNoSpecifiedTests=false -Dtest=NoUnitTestsInThisRun -Dsurefire.failIfNoSpecifiedTests=false
  • mvn -B verify -pl :openmetadata-integration-tests -am -Dspring-boot.repackage.skip=true -Pmysql-elasticsearch -DintegrationTests.lane=rdf '-Dit.test=<34 classes>' -Dfailsafe.failIfNoSpecifiedTests=false -Dtest=NoUnitTestsInThisRun -Dsurefire.failIfNoSpecifiedTests=false
  • mvn -B verify -pl :openmetadata-integration-tests -am -Dspring-boot.repackage.skip=true -Pcache-tests -DintegrationTests.lane=parallel -Dit.test=AlertStateIT,BundleWarmupCertificationIT,ContainerCacheCorrectnessIT,EntityCacheWriteOrderIT,OneTransactionFlushAtomicityIT,RelationshipCacheInvalidationIT,TagRenameCacheIT,UncachedReadIT -Dfailsafe.failIfNoSpecifiedTests=false -Dtest=NoUnitTestsInThisRun -Dsurefire.failIfNoSpecifiedTests=false
  • mvn -B verify -pl :openmetadata-integration-tests -am -Dspring-boot.repackage.skip=true -Pcache-tests -DintegrationTests.lane=global-state -Dit.test=CredentialRedisDownIT,CredentialRedisNoRoundTripIT,SessionRedisMultiNodeIT -Dfailsafe.failIfNoSpecifiedTests=false -Dtest=NoUnitTestsInThisRun -Dsurefire.failIfNoSpecifiedTests=false
  • mvn -B verify -pl :openmetadata-integration-tests -am -Dspring-boot.repackage.skip=true -Ppostgres-opensearch -DintegrationTests.lane=parallel -Dit.test=FlattenedChildrenHighlightSearchIT,InheritedFieldPropagationRecoveryIT -Dfailsafe.failIfNoSpecifiedTests=false -Dtest=NoUnitTestsInThisRun -Dsurefire.failIfNoSpecifiedTests=false
  • mvn -B verify -pl :openmetadata-integration-tests -am -Dspring-boot.repackage.skip=true -Ppostgres-opensearch -DintegrationTests.lane=global-state -Dit.test=PatchTableEmbeddingIT -Dfailsafe.failIfNoSpecifiedTests=false -Dtest=NoUnitTestsInThisRun -Dsurefire.failIfNoSpecifiedTests=false
Impacted, not run locally (2)
  • RdfCatalogScaleIT → only with -DrdfCatalogScale=true, which no CI lane sets
  • OntologyScaleIT → nightly: openmetadata-nightly k8s-java-it (scale-it)
Commands
mvn -B package -pl openmetadata-mcp,openmetadata-service -am -Dspring-boot.repackage.skip=true -Dtest=AgentSparqlQueryInspectorTest,AgentSparqlQueryValidatorTest,OntologySparqlQueryServiceTest,SparqlFederationGuardTest,SparqlQueryToolTest,SparqlQueryWalkerTest -Dsurefire.failIfNoSpecifiedTests=false
mvn -B verify -pl :openmetadata-integration-tests -am -Dspring-boot.repackage.skip=true -Pmysql-elasticsearch -DintegrationTests.lane=parallel -Dit.test=GlossaryOntologyQueryIT,OntologyDraftQueryIT -Dfailsafe.failIfNoSpecifiedTests=false -Dtest=NoUnitTestsInThisRun -Dsurefire.failIfNoSpecifiedTests=false
mvn -B verify -pl :openmetadata-integration-tests -am -Dspring-boot.repackage.skip=true -Pmysql-elasticsearch -DintegrationTests.lane=rdf -Dit.test=AgentSparqlResourceIT,RdfMcpKnowledgeGraphIT,RdfResourceIT -Dfailsafe.failIfNoSpecifiedTests=false -Dtest=NoUnitTestsInThisRun -Dsurefire.failIfNoSpecifiedTests=false

@gitar-bot

gitar-bot Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Code Review ✅ Approved

🔴 High risk · The new SPARQL traversal and execution denial govern server-side network access; a missed query position could still let callers trigger requests to internal hosts.

Closes the SPARQL SERVICE bypass by routing federation checks through a shared walker that follows expressions, EXISTS/NOT EXISTS blocks, subqueries and bare EXISTS elements, and disables HTTP SERVICE in the in-process ontology executor. No issues found.

Verification

Rules No rules evaluated

Functional validation Not enabled

Set up

Auto-approval Not enabled

Set up

For more verification details, comment gitar display:verbose.

Options

Display: compact → Showing compact verification results.

Comment with these commands to change the behavior for this request:

Compact
gitar display:verbose         

Was this helpful? React with 👍 / 👎 | Powered by Gitar — free for open source

@pmbrull
pmbrull merged commit a73cd43 into main Nov 6, 2026
66 of 68 checks passed
@pmbrull
pmbrull deleted the pmbrull/sparql-service-in-exists branch November 6, 2026 10:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Ingestion safe to test Add this label to run secure Github workflows on PRs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SparqlFederationGuard may miss SERVICE inside EXISTS, aggregates, and ORDER BY on the admin endpoint

3 participants